package icegps.com.pingdj.activity;

import android.content.Intent;
import android.graphics.Paint;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.OnClick;
import icegps.com.pingdj.App;
import icegps.com.pingdj.R;
import icegps.com.pingdj.bean.LocationStatus;
import icegps.com.pingdj.bean.PickerBean;
import icegps.com.pingdj.bean.WorkBean;
import icegps.com.pingdj.constant.Constant;
import icegps.com.pingdj.constant.Token;
import icegps.com.pingdj.data.ble.WriteHelper;
import icegps.com.pingdj.dialog.DialogPicker;
import icegps.com.pingdj.listener.OnUnitIndexListener;
import icegps.com.pingdj.utils.StringUtils;
import icegps.com.pingdj.utils.UnitUtils;
import icegps.com.pingdj.utils.Utils;
import icegps.com.pingdj.view.UnitTextView;
import icegps.com.pingdj.view.ValueTextView;

import static icegps.com.pingdj.constant.ActionKey.LAT;
import static icegps.com.pingdj.constant.ActionKey.LNG;
import static icegps.com.pingdj.constant.ActionKey.LOAD_TOKEN;
import static icegps.com.pingdj.constant.ActionKey.MEASURE_AVE_HEIGHT;
import static icegps.com.pingdj.constant.ActionKey.SAVE_TOKEN;
import static icegps.com.pingdj.constant.ActionKey.SLOPE;
import static icegps.com.pingdj.constant.ActionKey.SLOPE_START_HEIGHT;
import static icegps.com.pingdj.constant.ActionKey.TITLE;

/**
 * Created by 111 on 2018/3/28.
 */

public class SlopeActivity2 extends BaseActivity implements OnUnitIndexListener {
    @BindView(R.id.tv_current_height)
    ValueTextView tvCurrentHeight;
    @BindView(R.id.tv_plane_set_value_unit)
    UnitTextView tvPlaneSetValueUnit;
    @BindView(R.id.tv_slope_start_height)
    ValueTextView tvSlopeStartHeight;
    @BindView(R.id.tv_slope_start_height_unit)
    UnitTextView tvSlopeStartHeightUnit;
    @BindView(R.id.ll_slope_start_height)
    LinearLayout llSlopeStartHeight;
    @BindView(R.id.tv_slope_end_height)
    ValueTextView tvSlopeEndHeight;
    @BindView(R.id.tv_slope_end_height_unit)
    UnitTextView tvSlopeEndHeightUnit;
    @BindView(R.id.ll_slope_end_height)
    LinearLayout llSlopeEndHeight;
    @BindView(R.id.tv_start_end_difference)
    ValueTextView tvStartEndDifference;
    @BindView(R.id.tv_start_end_difference_unit)
    UnitTextView tvStartEndDifferenceUnit;
    @BindView(R.id.ll_start_end_difference)
    LinearLayout llStartEndDifference;
    @BindView(R.id.tv_start_end_distance)
    ValueTextView tvStartEndDistance;
    @BindView(R.id.tv_start_end_distance_unit)
    UnitTextView tvStartEndDistanceUnit;
    @BindView(R.id.ll_start_end_distance)
    LinearLayout llStartEndDistance;
    @BindView(R.id.tv_gradient)
    ValueTextView tvGradient;
    @BindView(R.id.tv_gradient_unit)
    UnitTextView tvGradientUnit;
    @BindView(R.id.ll_gradient)
    LinearLayout llGradient;
    @BindView(R.id.tv_slope_percent)
    ValueTextView tvSlopePercent;
    @BindView(R.id.tv_slope_percent_unit)
    UnitTextView tvSlopePercentUnit;
    @BindView(R.id.ll_slope_percent)
    LinearLayout llSlopePercent;
    @BindView(R.id.tv_hint)
    TextView tvHint;
    @BindView(R.id.tv_confirm)
    TextView tvConfirm;
    private long loadToken;
    private DialogPicker dialogPicker;
    private LocationStatus locationStatus;
    private boolean isFirst = true;
    private double measureAveHeight;
    private Long saveToken;
    private String slopeStartHeight;
    private double lat;
    private double lng;
    private double startHeight;
    private double endHeight;
    private WorkBean workBean;

    @Override
    protected String setTitle() {
        return getString(R.string.do_slope);
    }

    @Override
    protected void init() {
        workBean = new WorkBean();
        getIntentExtra();
        setTvData();
        setMeasureTvAndSlopeTv(measureAveHeight);
        WriteHelper.write(WriteHelper.GRADER + "1");

        dialogPicker = new DialogPicker(activity);
        dialogPicker.setOnUnitIndexListener(this);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        WriteHelper.write(WriteHelper.GRADER + "0");
    }

    private void getIntentExtra() {
        loadToken = getIntent().getLongExtra(LOAD_TOKEN, System.currentTimeMillis());
        saveToken = Token.CONTINUE_WORK_TOKEN;
        measureAveHeight = getIntent().getDoubleExtra(MEASURE_AVE_HEIGHT, Constant.measureAveHeight);
        slopeStartHeight = getIntent().getStringExtra(SLOPE_START_HEIGHT);
        lat = getIntent().getDoubleExtra(LAT, 0);
        lng = getIntent().getDoubleExtra(LNG, 0);
    }

    private void setTvData() {
        tvSlopeStartHeight.setText(UnitUtils.HEIGHT, deviceStatus.getHeight(), Double.parseDouble(slopeStartHeight));
        tvSlopeEndHeight.setText(tvSlopeStartHeight.getText().toString());
    }

    private void setMeasureTvAndSlopeTv(double value) {
        tvSlopeEndHeight.setText(UnitUtils.HEIGHT, deviceStatus.getHeight(), value);
        tvSlopeEndHeight.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG); //下划线
        tvSlopeEndHeight.getPaint().setAntiAlias(true);//抗锯齿
    }

    @Override
    protected int setLayout() {
        return R.layout.activity_slope2;
    }

    @OnClick({R.id.ll_slope_end_height, R.id.tv_confirm})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_slope_end_height:
                setAveSetHeight();
                break;
            case R.id.tv_confirm:
                if (status!=4){
                    Utils.showToast(getString(R.string.location_status_do_no_user));
                    return;
                }
                float currentHight = Float.parseFloat(tvCurrentHeight.getText().toString());
                float planeSetHeight = Float.parseFloat(tvSlopeEndHeight.getText().toString());
                if (Math.abs(currentHight - planeSetHeight) > 10) {
                    Utils.showToast(getString(R.string.not_more_than_ten_meters));
                    return;
                }
                startWork();
                break;
        }
    }

    private void startWork() {
        if (locationStatus == null) {
            Utils.showToast(getString(R.string.location_status_do_no_user));
            return;
        }
        String s = workBean
                .setId(saveToken)
                .setWorkAction(2)
                .setType(SLOPE)
                .setTime(System.currentTimeMillis())
                .setStartLongitude(lng)
                .setStartLatitude(lat)
                .setStartSetHeight(Float.parseFloat(tvSlopeStartHeight.getText().toString()))
                .setEndLongitude(locationStatus.getLongitude())
                .setEndLatitude(locationStatus.getLatitude())
                .setEndSetHeight(Float.parseFloat(tvSlopeEndHeight.getText().toString()))
                .setOffset(0).toString();

        WriteHelper.write(WriteHelper.GRADER + s);
        App.getInstance().getDaoSession().getWorkBeanDao().insertOrReplace(workBean);
        Intent intent = new Intent(activity, WorkMapActivity.class);
        intent.putExtra(LNG, workBean.getStartLongitude());
        intent.putExtra(LAT, workBean.getStartLatitude());
        intent.putExtra(TITLE, getString(R.string.do_slope));
        intent.putExtra(LOAD_TOKEN, loadToken);
        intent.putExtra(SAVE_TOKEN, saveToken);
        startActivity(intent);
        finish();
    }

    private void setAveSetHeight() {
        int[] indexs = new int[10];
        String s = tvSlopeEndHeight.getText().toString();
        if (s.contains("-")) {
            indexs[0] = 1;
            s = s.replace("-", "");
        } else {
            indexs[0] = 0;
        }
        for (int i = 0; i < s.length(); i++) {
            String ss = String.valueOf(s.charAt(s.length() - 1 - i));
            if (ss.equals(".")) {
                indexs[indexs.length - 2 - i] = 0;
            } else {
                indexs[indexs.length - 2 - i] = Integer.parseInt(ss);
            }
        }
        ArrayList<PickerBean> arrayList = new ArrayList<>();
        String[] symbol = {"+", "-"};
        String[] values = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9"};
        PickerBean p1 = new PickerBean(symbol, DialogPicker.PICKER_VIEW, indexs[0]);
        PickerBean p2 = new PickerBean(values, DialogPicker.PICKER_VIEW, indexs[1]);
        PickerBean p3 = new PickerBean(values, DialogPicker.PICKER_VIEW, indexs[2]);
        PickerBean p4 = new PickerBean(values, DialogPicker.PICKER_VIEW, indexs[3]);
        PickerBean p5 = new PickerBean(values, DialogPicker.PICKER_VIEW, indexs[4]);
        PickerBean p6 = new PickerBean(new String[]{"."}, DialogPicker.TEXT_VIEW, indexs[5]);
        PickerBean p7 = new PickerBean(values, DialogPicker.PICKER_VIEW, indexs[6]);
        PickerBean p8 = new PickerBean(values, DialogPicker.PICKER_VIEW, indexs[7]);
        PickerBean p9 = new PickerBean(values, DialogPicker.PICKER_VIEW, indexs[8]);
        PickerBean p10 = new PickerBean(new String[]{tvSlopeEndHeightUnit.getText().toString()}, DialogPicker.TEXT_VIEW, indexs[9]);
        arrayList.add(p1);
        arrayList.add(p2);
        arrayList.add(p3);
        arrayList.add(p4);
        arrayList.add(p5);
        arrayList.add(p6);
        arrayList.add(p7);
        arrayList.add(p8);
        arrayList.add(p9);
        arrayList.add(p10);

        dialogPicker.setLayoutOrder(arrayList, llSlopeEndHeight.getId());
        dialogPicker.show();

    }

    private void setTvDifference() {
        endHeight = Double.parseDouble(tvSlopeEndHeight.getText().toString());
        startHeight = Double.parseDouble(tvSlopeStartHeight.getText().toString());
        double difference = endHeight - startHeight;
        tvStartEndDifference.setText(UnitUtils.HEIGHT, deviceStatus.getHeight(), difference);
    }

    @Override
    public void onUnitIndex(int viewId, int[] selindex, String[] values) {
        String value = "";
        for (String s : values) {
            value += s;
        }
        if (TextUtils.isEmpty(value)) value = "0";
        float antennaLocation = Float.parseFloat(value);
        WriteHelper.write(WriteHelper.SET_ANTENNAP + value);
        tvSlopeEndHeight.setText(StringUtils.setAccuracy(antennaLocation, 3));
        setTvDifference();
    }


    @Override
    public void onAnalysisHexLocationData(LocationStatus locationStatus) {
        super.onAnalysisHexLocationData(locationStatus);
        this.locationStatus = locationStatus;
        tvCurrentHeight.setText(StringUtils.setAccuracy(locationStatus.getAltitude(), 3));
        if (measureAveHeight == 0 && isFirst) {
            isFirst = false;
            setMeasureTvAndSlopeTv(locationStatus.getAltitude());
        }
        double distance = getDistance(lat, lng, locationStatus.getLatitude(), locationStatus.getLongitude());
        tvStartEndDistance.setText(UnitUtils.LENGTH, deviceStatus.getLength(), distance);

        double gradient = Math.atan((endHeight - startHeight) / distance);
        tvGradient.setText(StringUtils.setAccuracy(gradient, 3));

        double percent = (endHeight - startHeight) / distance * 1000;
        tvSlopePercent.setText(StringUtils.setAccuracy(percent, 3));

        if (workBean != null) {
            workBean
                    .setStartEndDistance(distance)
                    .setGradient(gradient)
                    .setSlopePercent(percent);
        }

    }


    private float EARTH_RADIUS = 6378137.0f;

    //单位:米
    private double getDistance(double lat1, double lng1, double lat2, double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2.0 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2.0), 2.0) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2.0), 2.0)));
        s *= EARTH_RADIUS;
        return s;
    }

    private double rad(double d) {
        return d * Math.PI / 180.0;
    }

}
